package config

import (
	"fmt"
	"log"
	"path/filepath"
	"runtime"
	"time"

	"github.com/spf13/viper"
)

type JWTConfig struct {
	Issuer string        `mapstructure:"iss"`
	Hours  time.Duration `mapstructure:"hours"`
	Secret string        `mapstructure:"secret"`
}

var GlobalJWTConfig JWTConfig

type ServerConfig struct {
	Host string `mapstructure:"host"`
	Port string `mapstructure:"port"`
}

var GlobalServerConfig ServerConfig

type DataBaseConfig struct {
	Host     string `mapstructure:"host"`
	Port     uint64 `mapstructure:"port"`
	Driver   string `mapstructure:"driver"`
	Username string `mapstructure:"username"`
	Password string `mapstructure:"password"`
	Dbname   string `mapstructure:"dbname"`
}

var GlobalDataBaseConfig DataBaseConfig

type RedisConfig struct {
	Host     string `mapstructure:"host"`
	Port     uint64 `mapstructure:"port"`
	Password string `mapstructure:"password"`
	DB       int    `mapstructure:"db"`
}

var GlobalRedisConfig RedisConfig

func init() {
	_, filePath, _, _ := runtime.Caller(0)
	dir := filepath.Dir(filePath)
	// fmt.Printf("当前被执行Go文件的目录: %s\n", dir)
	// viper.SetConfigName("config.yaml") // 配置文件名
	// viper.AddConfigPath(filePath)      // 配置文件路径
	viper.SetConfigFile(dir + "\\config.yaml") // 配置文件名
	err := viper.ReadInConfig()                // 读取配置文件
	if err != nil {
		panic(fmt.Errorf("fatal error config file: %s", err))
	}

	err = viper.UnmarshalKey("jwt", &GlobalJWTConfig)
	if err != nil {
		log.Fatal(err)
	}
	err = viper.UnmarshalKey("server", &GlobalServerConfig)
	if err != nil {
		log.Fatal(err)
	}
	err = viper.UnmarshalKey("database", &GlobalDataBaseConfig)
	if err != nil {
		log.Fatal(err)
	}
	err = viper.UnmarshalKey("redis", &GlobalRedisConfig)
	if err != nil {
		log.Fatal(err)
	}
}
